package ar.edu.unq.edp.futbol.usuarios;

import java.util.concurrent.CyclicBarrier;
import org.hibernate.Session;
import org.hibernate.Transaction;

public abstract class UsuarioSimple<T> extends UsuarioPersistente<T>{
	private CyclicBarrier barrier;
	
	public UsuarioSimple( CyclicBarrier barrier) {
		this.setBarrier(barrier);
	}

	public abstract T ejecutarTarea(Session session);
	
	public void cerrarSesion(Session session, Transaction transaction, T obj){	
		try {
			save(session,obj);
			commitearTransaccion(transaction);
		} catch (RuntimeException e) {
			rollback(transaction);
			throw e;
		} finally {
			try{
				session.close();
			} catch (Exception e){}
		}
	}

	public void run() {
		Session session = pedirSesion();
		Transaction transaction = transaccionar(session);
		try {
			barrier.await();
		} catch (Exception e) {
			throw new RuntimeException();
		}
		T obj = ejecutarTarea(session);
		cerrarSesion(session, transaction, obj);
	}
	//TODO extraer el barrier del run, ejecutarTarea en un try y meterlo en el cerrarSession 
	
	
	//Setters && getters

	public void setBarrier(CyclicBarrier barrier) {
		this.barrier = barrier;
	}

	public CyclicBarrier getBarrier() {
		return barrier;
	}

}
